<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
    :defaultConfig="toolbarConfig" :mode="mode"
      ref="toolbar" />
    <Editor style="height: 500px; overflow-y: hidden;" v-model="html"
    :defaultConfig="editorConfig" :mode="mode"
      @onCreated="onCreated" @onChange="onchange" ref="editor"/>
  </div>
</template>
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { uploadCourseImage } from '@/services/course';

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  props: ['value'],
  data() {
    return {
      editor: null,
      html: this.value,
      toolbarConfig: {
        excludeKeys: [
          'insertVideo',
          'uploadVideo',
        ],
      },
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: '/api/upload-image',
            customUpload: async (file, insertImgFn) => {
              const fd = new FormData();
              fd.append('file', file);
              const { data } = await uploadCourseImage(fd, (event) => {
                this.percentage = Math.floor((event.loaded / event.total) * 100);
              });
              if (data.code === '000000') {
                const filename = data.data.name;
                insertImgFn(filename, '', '');
                this.$message.success('图片上传成功');
              } else {
                this.$message.error('图片上传失败');
              }
            },
          },
        },
      },
      mode: 'default', // or 'simple'
    };
  },
  watch: {
    value(val) {
      this.html = val;
    },
  },
  methods: {
    onchange() {
      this.$emit('input', this.html);
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
      // 一定要用 Object.seal() ，否则会报错
    },
  },
  mounted() {

  },
  beforeDestroy() {
    // eslint-disable-next-line
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>
